// components/vcode-countdown/vcode-countdown.js
let TimeOut = null;
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        loading: { //是否加载加载中
            type: Boolean,
            value: false
        },
        start: { //是否开始倒计时
            type: Boolean,
            value: false
        },
        color: { //文本颜色
            type: String,
            value: "var(--color-student-primary)"
        }
    },

    /*
    * 数据监听
    * */
    observers: {
        "loading": function (val) {
            if (val) {
                let isLoading = this.data._smsButton.isLoading;
                let isDisabled = this.data._smsButton.isDisabled;
                if (isLoading || isDisabled) { //防重复
                    return false
                } else {
                    this.setData({
                        "_smsButton.isLoading": true,
                        "_smsButton.isDisabled": true
                    })
                }
            }
        },
        "start": function (val) {
            if (val) {
                this.setData({"_smsButton.isLoading": false});
                clearTimeout(TimeOut);
                this._startTimeOut()
            }
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        _smsButton: {
            isLoading: false, //是否正在发送验证码
            isDisabled: false, //是否禁用按钮
            text: "发送验证码", //验证码文本
            times: 120  //验证码获取间隔时间
        },
    },

    ready: function () {
        this._saveTime = this.data._smsButton.times; //保存初始信息
    },

    // 在组件实例被从页面节点树移除时执行
    detached: function() { //页面跳转时清楚定时器
        clearTimeout(TimeOut)
    },

    /**
     * 组件的方法列表
     */
    methods: {

        /*
       * 发送验证码
       * */
        onBottomClick: function () {
            this.triggerEvent("sendSms", {});
        },

        /*
        * 倒计时
        * */
        _startTimeOut: function () {
            const that = this;
            let times = this.data._smsButton.times;
            let saveTimes = this._saveTime;
            TimeOut = setTimeout(function () {
                if (times > 0) {
                    times --;
                    that.data._smsButton.times = times
                    that.setData({"_smsButton.text": "重新发送(" + times + "s)"});
                    that._startTimeOut();
                } else {
                    that.data._smsButton.times = saveTimes;
                    that.setData({
                        "_smsButton.text": "发送验证码",
                        "_smsButton.isDisabled": false
                    })
                    clearTimeout(TimeOut);
                }
            }, 1000)
        },
    }
})
